package com.jy.modules.cims.component.credit.creditor.transferee;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.sysAssist.AbstractDueExecuteTaskManager;
import com.jy.modules.cims.component.sysAssist.CSysAssistImpl;
import com.jy.modules.cims.data.dao.DealDao;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.credit.CreditApplyDto;
import com.jy.modules.cims.data.dto.credit.CreditApplyResultDto;
import com.jy.modules.cims.data.interact.core.credit.request.CreditForGetConstraint;
import com.jy.modules.cims.data.interact.core.credit.request.Request4036DTO;
import com.jy.modules.cims.interact.ICInteract;

/**
 * @description 抽象的债权受让处理实现类组件。
 * @author shengzhoutao
 * @date 2015-07-07
 */
public abstract class AbstractCreditorTransfereeDeal implements ICreditorTransfereeDeal {
	private static final Logger logger = LoggerFactory.getLogger(AbstractCreditorTransfereeDeal.class);
	//private static final String METHOD_CANCELSRCREDITSTOCORE = "cancelSRCreditsToCore";// 取消发送给核心系统的受让的债权处理方法名

	@Autowired
	public DealDao dealDao;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.CSysAssistImpl")
	private CSysAssistImpl csysAssistimpl;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.credit.creditor.transferee.TransgereeDao")
	private TransgereeDao transgereeDao;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.DueExecuteTaskManager")
	public AbstractDueExecuteTaskManager abstractDueExecuteTaskManager;

	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CCInteractImpl")
	public ICInteract iCInteract;

	/**
	 * @description 创建请求
	 * @param applyDto
	 *            债权申请实体
	 * @author shengzhoutao
	 * @date 2015-07-07
	 */
	public void createApply(CreditApplyDto applyDto) throws Exception {
		logger.info("====================createApply====================");

		String dealCode = getDealCode();// 债权受让流水号
		applyDto.setDealCode(dealCode);
		// 创建请求
		transgereeDao.createApply(applyDto);
	}
	/**
	 * 
	 * @Description 受让流水号生成
	 * @author zhangmi
	 * @date 2016-7-7
	 */
	@Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 5)
	private String getDealCode(){
		return csysAssistimpl.getBizNo(CimsConstant.BIZNO_TYPE_CRTI);
	}
	
	/**
	 * @description 撤销请求
	 * @param applyDto
	 *            债权申请实体
	 */
	public void cancelApply(CreditApplyDto applyDto) throws Exception {
		logger.info("====================cancelApply====================");

		if (!SimpleStringUtils.hasText(applyDto.getDealCode())) {
			logger.info("交易流水号为空！不可以做撤销删除！");
			return;
		}

		String dealCode = applyDto.getDealCode();// 交易流水

		List<String> dealCodeList = new ArrayList<String>();
		dealCodeList.add(dealCode);
		List<DealDto> dealDtoList = dealDao.getCooperorgDealByDealCodeList(dealCodeList);
		dealCodeList = null;
		if (CollectionsUtils.isEmpty(dealDtoList)) {
			throw new Exception(MessageFormat.format("根据交易流水号[{0}]没有查询到该交易信息！", new Object[] { dealCode }));
		}

		DealDto dealDto = dealDtoList.get(0);
		if (!CimsConstant.DEAL_TYPE_CREDIT_IN.equals(dealDto.getDealType())) {
			throw new Exception(MessageFormat.format("根据交易流水号[{0}]的交易类型不符合删除或撤销要求！", new Object[] { dealCode }));
		}

		if (CimsConstant.DEAL_STATUS_CREATE.equals(dealDto.getCooperativeAgencyDealStatus())
				|| CimsConstant.DEAL_STATUS_WAY.equals(dealDto.getCooperativeAgencyDealStatus())) {
			// 交易状态：02-在途，调用接口
			if (CimsConstant.DEAL_STATUS_WAY.equals(dealDto.getCooperativeAgencyDealStatus())) {
				//abstractDueExecuteTaskManager.addDueExecuteTask(METHOD_CANCELSRCREDITSTOCORE, new java.util.Date(), dealCode);
				cancelSRCreditsToCoreByDealCode(dealCode) ;
				// 删除交易流水
				transgereeDao.deleteCooperorgDeal(dealCode);
			} else{
				transgereeDao.deleteCreditDetail(dealCode);
			}

			// 删除交易流水
			// transgereeDao.deleteCooperorgDeal(dealCode);
		} else {
			throw new Exception(MessageFormat.format("根据交易流水号[{0}]的交易状态不符合删除或撤销要求！", new Object[] { dealCode }));
		}
	}

	/**
	 * @description 发送请求
	 * @param applyDto
	 *            债权申请实体
	 * @author shengzhoutao
	 * @date 2015-07-07
	 */
	public void sendApplyToConsult(CreditApplyDto applyDto) throws Exception {
		logger.info("====================sendApplyToConsult====================");

		// ...
	}

	/**
	 * @description 确认结果
	 * @param applyDto
	 *            债权申请实体
	 * @param applyResultDto
	 *            债权申请结果实体
	 * @throws Exception
	 * @author shengzhoutao
	 * @date 2015-07-07
	 */
	public void confirmApplyResult(CreditApplyDto applyDto, CreditApplyResultDto applyResultDto) throws Exception {
		logger.info("====================confirmApplyResult====================");

		// 确认结果(新增债权流水, 新增债权明细)
		transgereeDao.confirmApplyResult(applyDto, applyResultDto);
	}
	
	/**
	 * @description 调用核心系统撤销受让的债权
	 * @author shengzhoutao
	 * @date 2015-07-21
	 * @param dealCode
	 *            交易流水号
	 */
	private void cancelSRCreditsToCoreByDealCode(final String dealCode) {
		// 根据交易流水号查询债权明细
		DealDto dealDto = new DealDto();
		dealDto.setDealCode(dealCode);
		List<CreditDetailDto> creditDetailList = dealDao.getDealDetailByCreditList(SearchParamUtil.getSearchParam(dealDto));
		if (CollectionsUtils.isEmpty(creditDetailList)) {
			return;
		}

		// 调用撤销接口
		Request4036DTO request = new Request4036DTO();
		List<CreditForGetConstraint> creditList = tranCreditForGetConstraint(dealCode, creditDetailList);
		request.setCreditList(creditList);
		iCInteract.cancelSRCreditsToCore(request);

		creditList = null;
		request = null;
	}
	
	/**
	 * 
	 * @param dealCode
	 * @param creditDetailList
	 * @return
	 */
	private List<CreditForGetConstraint> tranCreditForGetConstraint(final String dealCode, final List<CreditDetailDto> creditDetailList) {
		List<CreditForGetConstraint> creditList = new ArrayList<CreditForGetConstraint>();
		CreditForGetConstraint creditForGetConstraint = null;
		for (CreditDetailDto creditDetailDto : creditDetailList) {
			creditForGetConstraint = new CreditForGetConstraint();
			creditForGetConstraint.setBatchId(dealCode);// 批次号
			creditForGetConstraint.setContractNo(creditDetailDto.getContractCode());// 合同编号
			creditForGetConstraint.setOtherCreditId(creditDetailDto.getCreditCode());// 债权编号
			creditList.add(creditForGetConstraint);
		}
		creditForGetConstraint = null;
		return creditList;
	}
}
